# 表单验证
import wtforms
from wtforms.validators import Email, Length, EqualTo
from models import User
from exts import redis

# Form：用来验证用户输入的数据是否合法
class RegisterForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message='Invalid email address.')])
    captcha = wtforms.StringField(validators=[Length(min=4, max=6, message="Captcha must be between 4 and 6 characters.")])
    username = wtforms.StringField(validators=[Length(min=4, max=25, message="Username must be between 4 and 25 characters.")])
    password = wtforms.PasswordField(validators=[Length(min=8, max=72, message="Password must be at least 8 characters long.")])
    confirm_password = wtforms.PasswordField(validators=[EqualTo('password', message='Passwords do not match.')])

    # 验证邮箱是否已经被注册
    def validate_email(self, email):
        if User.query.filter_by(email=email.data).first():
            raise wtforms.ValidationError("This email is already in use.")

    # 验证用户名是否已经被注册
    def validate_username(self, username):
        if User.query.filter_by(username=username.data).first():
            raise wtforms.ValidationError("This username is already taken.")

    # 验证验证码是否正确
    def validate_captcha(self, captcha):
        email = redis.get(self.email.data)
        if not email:
            raise wtforms.ValidationError("Incorrect captcha.")
        redis_captcha = email.decode('utf-8')
        if not redis_captcha == captcha.data:
            raise wtforms.ValidationError("Incorrect captcha.")
        else:
            # 验证通过，删除验证码
            redis.delete(self.email.data)


class LoginForm(wtforms.Form):
    username = wtforms.StringField(validators=[Length(min=4, max=25, message="Username must be between 4 and 25 characters.")])
    password = wtforms.PasswordField(validators=[Length(min=8, max=72, message="Password must be at least 8 characters long.")])

class QuestionForm(wtforms.Form):
    title = wtforms.StringField(validators=[Length(min=1, max=256, message="Title must be between 1 and 256 characters.")])
    content = wtforms.StringField(validators=[Length(min=1, max=2048, message="Content must be between 1 and 2048 characters.")])

class AnswerForm(wtforms.Form):
    content = wtforms.StringField(validators=[Length(min=1, max=256, message="Content must be between 1 and 256 characters.")])